package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //处理查询所有角色请求
    @RequestMapping("/list")
    @RequiredPermission(name = "角色列表",expression = "role:list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);

        return "role/list";//找视图  "/WEB-INF/views/dept/list.jsp"
    }

    @RequestMapping("/delete")
    @RequiredPermission(name = "角色删除",expression = "role:delete")
    public String delete(Long id){
        if(id!=null){
            roleService.delete(id);
        }
        return "redirect:/role/list";  //重定向
    }
    //去新增或去修改页面
    @RequestMapping("/input")
    @RequiredPermission(name = "角色新增或修改",expression = "role:saveOrUpdate")
    public String input(Long id,Model model){

        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);
        //回显权限选择框左边的权限
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions", permissions);

        if(id!=null){
            Role role = roleService.get(id);
            model.addAttribute("role",role);

            List<Permission> permissions2 = roleService.selectByRoleId(id);
            model.addAttribute("permissions2",permissions2);
        }
        return "role/input";
    }
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "角色新增或修改",expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        if(role.getId()==null){
            roleService.save(role,ids);
        }else{
            roleService.update(role,ids);
        }
        return "redirect:/role/list";
    }



}
